package com.twh.www.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    public RedisTemplate<String, Object> redisTemplate;

    private static final String GOODS_PAGE_KEY = "goods:page:"; // 商品分页数据的键前缀
    private static final String GOODS_TOTAL_KEY = "goods:total"; // 商品总数统计的键

    //"goods:search:" + keyword + ":" + pageNum;
    private static final String GOODS_SEARCH_PAGE_KEY = "goods:search:"; // 商品总数统计的键
    private static final long CACHE_EXPIRE_TIME = 1; // 缓存过期时间（分钟）

    // 缓存商品分页数据
    public void cacheGoodsPage(int page, List<?> goods) {
        String key = GOODS_PAGE_KEY + page;
        redisTemplate.opsForValue().set(key, goods, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    public void cacheSearchGoodsPage(String keyword,int page, List<?> goods) {
        String key = GOODS_SEARCH_PAGE_KEY +keyword+":"+ page;
        redisTemplate.opsForValue().set(key, goods, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    // 获取缓存的商品分页数据
    public List<?> getGoodsPage(int page) {
        String key = GOODS_PAGE_KEY + page;
        return (List<?>) redisTemplate.opsForValue().get(key);
    }

    // 缓存商品总数
    public void cacheTotal(long total) {
        redisTemplate.opsForValue().set(GOODS_TOTAL_KEY, total, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    // 获取缓存的商品总数
    public Long getTotal() {
        Object value = redisTemplate.opsForValue().get(GOODS_TOTAL_KEY);
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        }
        return (Long) value;
    }

    // 清除商品相关的所有缓存
    public void clearGoodsCache() {
        redisTemplate.delete(GOODS_TOTAL_KEY);
        // 这里可以添加清除所有分页缓存的逻辑
        // 实际项目中可能需要更复杂的缓存清理策略
    }
}